#include "transport.h"
#include "lwip/opt.h"
#include "lwip/arch.h"
#include "lwip/api.h"
#include "lwip/inet.h"
#include "lwip/sockets.h"
#include "string.h"

static int mysock;


////////////////////////////////////////////////////////////////////////////////
/// @brief  transport_sendPacketBuffer
/// @note   Send data in TCP mode.
/// @param  buf : data buff.
///         buflen : length.
/// @retval >=0: Send successfully <0: Send failed.
////////////////////////////////////////////////////////////////////////////////
int32_t transport_sendPacketBuffer( uint8_t* buf, int32_t buflen)
{
    int32_t rc;
    rc = write(mysock, buf, buflen);
    return rc;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  transport_getdata
/// @note   Receive in a blocking manner.
/// @param  buf : buff.
///         count: length.
/// @retval >=0: Send successfully <0: Send failed.
////////////////////////////////////////////////////////////////////////////////
int32_t transport_getdata(uint8_t* buf, int32_t count)
{
    int32_t rc;

    rc = recv(mysock, buf, count, 0);
    return rc;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  transport_open
/// @note   Open an interface and establish a connection with the server.
/// @param  char* servip:Server domain name.
///         int   port:  The port number
/// @retval >=0: Send successfully <0: Send failed.
////////////////////////////////////////////////////////////////////////////////
int32_t transport_open(int8_t* servip, int32_t port)
{
    int32_t* sock = &mysock;
    int32_t ret;
//  int32_t opt;
    struct sockaddr_in addr;

    memset(&addr, 0, sizeof(addr));
    addr.sin_len = sizeof(addr);
    addr.sin_family = AF_INET;

    addr.sin_port = PP_HTONS(port);

    addr.sin_addr.s_addr = inet_addr((const char*)servip);

    *sock = socket(AF_INET, SOCK_STREAM, 0);

    ret = connect(*sock, (struct sockaddr*)&addr, sizeof(addr));
    if(ret != 0) {

        close(*sock);

        return -1;
    }
    return *sock;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief  transport_close
/// @note   Close the socket.
/// @param  None.
/// @retval >=0: Send successfully <0: Send failed.
////////////////////////////////////////////////////////////////////////////////
int transport_close(void)
{
    int rc;
//  rc = close(mysock);
    rc = shutdown(mysock, SHUT_WR);
    rc = recv(mysock, NULL, (size_t)0, 0);
    rc = close(mysock);
    return rc;
}
